#include "sy_uwp_thread.h"

using namespace winrt;
using namespace Windows::Foundation;
using namespace std::chrono;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Graphics::Imaging;
using namespace Windows::Media::Ocr;

UWPWorker::UWPWorker():bitmap_(nullptr), lang_(nullptr), engine_(nullptr)
{
	//SetOcrEngineLang();
	if (engine_ == nullptr)
	{
		int dd = 2;
	}
}

UWPWorker::UWPWorker(winrt::Windows::Globalization::Language lang) : bitmap_(nullptr), lang_(lang), engine_(nullptr)
{
	SetOcrEngineLang(lang);
}

UWPWorker::~UWPWorker()
{
}

void UWPWorker::SetOcrEngineLang(winrt::Windows::Globalization::Language lang)
{
	lang_ = lang;

	engine_ = OcrEngine::TryCreateFromLanguage(lang_);
	
// 	if (engine_ == nullptr)
// 	{
// 	}
}

bool UWPWorker::HaveEngine()
{
	return engine_ != nullptr;
}

void UWPWorker::RecognizeBitmap(const Windows::Graphics::Imaging::SoftwareBitmap bitmap)
{
	if (!HaveEngine())
	{
		return;
	}
	{
		std::unique_lock<std::mutex> auto_locker(mutex_);
		bitmap_ = bitmap;
	}

	wait_condition_.notify_all();
}

IAsyncOperation<OcrResult> UWPWorker::AsyncOperate(SoftwareBitmap bitmap)
{
	OcrResult result = co_await engine_.RecognizeAsync(bitmap);
	return result;
}

void UWPWorker::stop()
{
	{
		std::unique_lock<std::mutex> auto_locker(mutex_);
		stop_ = true;
	}

	wait_condition_.notify_all();
}

void UWPWorker::run()
{
	init_apartment();



	while (!stop_)
	{
		std::unique_lock<std::mutex> auto_locker(mutex_);
		wait_condition_.wait(auto_locker);
		if (stop_)
		{
			break;
		}
		auto ret = AsyncOperate(bitmap_);
		auto ocr_ret = ret.get();
		auto lines = ocr_ret.Lines();
		QStringList ret_list;
		for (auto &line : lines)
		{
			auto one_line = QString::fromWCharArray(line.Text().c_str(), line.Text().size());
			//retStr.append(one_line.replace(' ', ""));
			one_line.append("\n");
			ret_list.append(one_line);
		}
		emit SignalReslut(ret_list);
	}


	uninit_apartment();
}